// main.js
import { createApp } from "vue";
import {
  createRouter,
  createWebHistory,
  createWebHashHistory,
} from "vue-router";
import routes from "./router";
import App from "./App.vue";
import { customLog } from "./utils/log";

let app = null;
let router = null;
let history = null;
// 👇 将渲染操作放入 mount 函数，子应用初始化时会自动执行
window.mount = () => {
  history = createWebHashHistory();
  router = createRouter({
    history,
    routes,
  });

  app = createApp(App);
  app.use(router);
  app.mount("#app");
};

/**
 * 应用渲染时执行
 * @param data 初始化数据
 */
window.addEventListener("mounted", (e) => {
  const data = e.detail.data;
  customLog("子应用已经渲染，收到的数据为：", data);
});

/**
 * 应用卸载时执行
 */
window.addEventListener("unmount", () => {
  customLog("子应用已经卸载");
});

// 👇 将卸载操作放入 unmount 函数，就是上面步骤2中的卸载函数
window.unmount = () => {
  app.unmount();
  history.destroy();
  app = null;
  router = null;
  history = null;
};

// 如果不在微前端环境，则直接执行mount渲染
if (!window.__MICRO_APP_ENVIRONMENT__) {
  customLog("我不在微前端环境中", "blue");
  window.mount();
}
if (window.__MICRO_APP_ENVIRONMENT__) {
  customLog("我在微前端环境中");
  customLog("我的真实window：", window.rawWindow);
  customLog("我的真实document：", window.rawDocument);
  customLog("main-app为我分配的应用名：", window.__MICRO_APP_NAME__);
  customLog("我的静态资源前缀：", window.__MICRO_APP_PUBLIC_PATH__);
  customLog("我的基础路径：", window.__MICRO_APP_BASE_ROUTE__);

  // 监听全局数据
  window.microApp.addGlobalDataListener((data) => {
    customLog("接收到全局数据：", data);
    return "ok";
  });
}
